package com.tsinghuabigdata.edu.ddmath.util;

import android.content.Context;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
import com.tsinghuabigdata.edu.ddmath.ZxApplication;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;

import java.io.IOException;

/**
 *
 */
public class PicassoUtil {

    private static Picasso.Builder mBuilder;
    private static Picasso mPicasso;
    private OkHttpClient okHttpClient;

    private PicassoUtil(){
        okHttpClient = new OkHttpClient();
        okHttpClient.interceptors().add( new TokenInterceptor() );
    }
    public static Picasso getPicasso(Context context){
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if( loginInfo != null && loginInfo.getAccessToken() != null ){
            if( mPicasso == null ){
                PicassoUtil mPicassoUtil = new PicassoUtil();
                if( mBuilder == null )
                    mBuilder = new Picasso.Builder( context ).downloader(new OkHttpDownloader( mPicassoUtil.okHttpClient ));
                mPicasso = mBuilder.build();
            }
            return mPicasso;
        }else{
            return Picasso.with( context );
        }
    }

    public static void init(){
        LoginInfo loginInfo = AccountUtils.getLoginUser();
        if( loginInfo != null && loginInfo.getAccessToken() != null ){
            PicassoUtil mPicassoUtil = new PicassoUtil();
            if( mBuilder == null ){
                mBuilder = new Picasso.Builder(ZxApplication.getApplication()).downloader(new OkHttpDownloader( mPicassoUtil.okHttpClient ));
            }else{
                mBuilder.downloader(new OkHttpDownloader( mPicassoUtil.okHttpClient ));
            }
            mPicasso = mBuilder.build();
        }
    }

    public class TokenInterceptor implements Interceptor {

        public TokenInterceptor() {
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder request = chain.request().newBuilder();
            try {
                LoginInfo loginInfo = AccountUtils.getLoginUser();
                if (loginInfo != null && loginInfo.getAccessToken() != null) {
                    request.addHeader("access_token", loginInfo.getAccessToken());
                }
            } catch (Exception ex) {
                AppLog.i("set token fault", ex);
            }
            return chain.proceed(request.build());
        }
    }
}
